﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using NUnit.Framework;
using XcoAppSpaces.Core;
using System.Threading;

namespace test.XcoAppSpaces.Core
{
	[TestFixture]
	class testXcoTimedAction
	{
		[Test]
		public void InvokeTimedAction_Delayed_Reschedule()
		{
			InvokeTimedAction(true, true);
		}

		[Test]
		public void InvokeTimedAction_Delayed_NoReschedule()
		{
			InvokeTimedAction(true, false);
		}

		[Test]
		public void InvokeTimedAction_NotDelayed_Reschedule()
		{
			InvokeTimedAction(false, true);
		}

		[Test]
		public void InvokeTimedAction_NotDelayed_NoReschedule()
		{
			InvokeTimedAction(false, false);
		}


		private void InvokeTimedAction(bool delayed, bool reschedule)
		{
			int test = (delayed ? 1 : 0);

			var timer = new XcoTimedAction(TimeSpan.FromMilliseconds(500), () =>
			{
				Interlocked.Increment(ref test);
				return (reschedule ? XcoTimedAction.Continuation.Reschedule : XcoTimedAction.Continuation.Stop);
			});

			if (delayed)
				timer.InvokeDelayed();
			else
				timer.Invoke();
			Thread.Sleep(100);
			Assert.AreEqual(1, test);
			Thread.Sleep(600);
			Assert.AreEqual((reschedule ? 2 : delayed ? 2 : 1), test);
		}
	}
}
